package com.geeklan.smart.utils;

import android.content.Context;
import android.net.Uri;
import android.os.Environment;

import com.geeklan.base.utils.MLog;
import com.geeklan.smart.MLMApplication;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtils {
    public static String createAppPhotoFolder() {
        // 获取公共图片目录
        File picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        // 创建应用专属文件夹
        File appFolder = new File(picturesDir, "MML");
        if (!appFolder.exists()) {
            boolean isCreated = appFolder.mkdirs();
            if (!isCreated) {
                MLog.e("AppPhotoFolder", "Failed to create directory: " + appFolder.getAbsolutePath());
                return null;
            }
        }
        return appFolder.getAbsolutePath();
    }

    public static String getExternalFilesDir(){
        File file = new File(MLMApplication.getApplication().getExternalFilesDir(null),System.currentTimeMillis() + ".jpg");
        return file.getAbsolutePath();
    }

    public static String extractFileNameWithoutExtension(String path) {
        if (path == null || path.isEmpty()) {
            return "";
        }

        // 找到最后一个斜杠的位置
        int lastSlashIndex = path.lastIndexOf("/");
        if (lastSlashIndex == -1 || lastSlashIndex == path.length() - 1) {
            return ""; // 如果没有斜杠或斜杠后无内容
        }

        // 提取文件名
        String fileName = path.substring(lastSlashIndex + 1);

        // 去掉扩展名
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex != -1) {
            fileName = fileName.substring(0, dotIndex);
        }

        return fileName;
    }

    public static File copyUriToFile(Context context,Uri uri) {
        try {
            File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "camera_image.jpg");
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            OutputStream outputStream = new FileOutputStream(file);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }

            inputStream.close();
            outputStream.close();

            return file;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
